package workers;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import workerUIs.StepFrame;

import com.ibm.mq.MQException;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

public class QueueDepthObserver {

	private Logger logger = Logger.getLogger(QueueDepthObserver.class.getCanonicalName());
	
	public void observeQueueDepth(final StepFrame frame, final String... queueNames) {
		final Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					MQQueueManager qm = new MQQueueManager(IMQConstants.MQM_NAME);
					boolean isRunning = true;
					while(isRunning) {
						try {
							List<MQQueue> queues = new ArrayList<MQQueue>();
							for (String qn : queueNames) {
								queues.add(qm.accessQueue(qn, IMQConstants.OPEN_OPTIONS));
							}
							boolean enableButton = true;
							for (MQQueue q : queues) {
								if (q.getCurrentDepth() <= 0) {
									enableButton = false;
								}
							}
							frame.getNextButton().setEnabled(enableButton);
							for (MQQueue q : queues) {
								q.close();
							}
							Thread.sleep(300);
						} catch(InterruptedException ie) {
							isRunning = false;
							logger.log(Level.SEVERE, "Interrupted: " + ie.getMessage());
						} catch (MQException e) {
							isRunning = false;
							logger.log(Level.SEVERE, "MQException: " + e.getMessage());
						}
					}
					qm.disconnect();
				} catch (MQException e) {
					logger.log(Level.SEVERE, "MQException: " + e.getMessage());
				}
			}
		});
		t.start();
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				t.interrupt();
			}
		});
	}
	
}
